package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private HttpSession session;

    @PostMapping(value = "/login",name = "员工登录")
    public ResultInfo login(@RequestBody Map<String,String> map){
        String username = map.get("username");
        String password = map.get("password");
        Employee employee = employeeService.login(username,password);
        //如果查询的员工不存在
        if (employee == null){
            return ResultInfo.error("您输入的用户名或密码错误!");
        }
        //存在,将其存入session域对象中
        session.setAttribute(Constant.SESSION_EMPLOYEE,employee);
        return ResultInfo.success(employee);
    }

    @PostMapping(value = "/logout",name = "退出员工登录")
    public ResultInfo logout(){
        //清理session中的用户信息
        session.invalidate();
        return ResultInfo.success("退出成功!");
    }
    @GetMapping(value = "/find",name = "查询所有员工")
    public ResultInfo findAll(String name){
        List<Employee> employeeList = employeeService.findAll(name);
        return ResultInfo.success(employeeList);
    }

    @PostMapping(name = "添加员工")
    public ResultInfo save(@RequestBody Employee employee){
        employeeService.save(employee);
        return ResultInfo.success(null);
    }

    @GetMapping(value = "/{id}",name = "修改员工回显数据")
    public ResultInfo findById(@PathVariable("id") Long id){
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    @PutMapping(name = "修改员工信息")
    public ResultInfo updateById(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }


}
